package com.github.sbb.sherry.primitives.api;

import java.util.Collections;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;

public class Rules implements Iterable<Rule> {

    private Set<Rule> ruleSet = new TreeSet<>();

    public Rules(Set<Rule> ruleSet) {
        this.ruleSet = new TreeSet<>(ruleSet);
    }

    public Rules(Rule... ruleSet) {
        Collections.addAll(this.ruleSet, ruleSet);
    }

    public void register(Rule... rules) {
        Objects.requireNonNull(rules);
        for (Rule rule : rules) {
            Objects.requireNonNull(rule);
            this.ruleSet.add(rule);
        }
    }

    public void unregister(Rule... rules) {
        Objects.requireNonNull(rules);
        for (Rule rule : rules) {
            Objects.requireNonNull(rule);
            this.ruleSet.remove(rule);
        }
    }

    public void unregister(final String ruleName) {
        Objects.requireNonNull(ruleName);
        Rule rule = findRuleByName(ruleName);
        if (rule != null) {
            unregister(rule);
        }
    }

    public boolean isEmpty() {
        return ruleSet.isEmpty();
    }

    public void clear() {
        ruleSet.clear();
    }

    public int size() {
        return ruleSet.size();
    }

    @Override
    public Iterator<Rule> iterator() {
        return ruleSet.iterator();
    }

    private Rule findRuleByName(String ruleName) {
        return ruleSet.stream()
            .filter(rule -> rule.name().equalsIgnoreCase(ruleName))
            .findFirst()
            .orElse(null);
    }
}
